package com.yunshipei.core.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.yunshipei.core.R;
import com.yunshipei.core.model.WaterMarkConfig;
import com.yunshipei.core.utils.SystemUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class WaterMarkView extends SurfaceView implements SurfaceHolder.Callback {

    private Thread thread;
    private TextPaint textPaint = new TextPaint();
    private int dx;  //水印左右间隔
    private int dy;  //水印上下间隔
    private int textColor;//水印颜色
    private int textSize;//水印字体大小
    private int degress;//水印旋转角度
    private float textAlpha;

    private List<String> texts = new ArrayList<>();

    public WaterMarkView(Context context) {
        this(context, null);
    }

    public WaterMarkView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WaterMarkView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.WaterMarkView);
        degress = typedArray.getInt(R.styleable.WaterMarkView_wm_degree, -30);
        dx = typedArray.getDimensionPixelSize(R.styleable.WaterMarkView_wm_dx, getResources().getDimensionPixelSize(R.dimen.wtm_default_dx));
        dy = typedArray.getDimensionPixelSize(R.styleable.WaterMarkView_wm_dy, getResources().getDimensionPixelSize(R.dimen.wtm_default_dy));
        textColor = typedArray.getColor(R.styleable.WaterMarkView_wm_textColor, getResources().getColor(R.color.wtm_default_text_color));
        textSize = typedArray.getDimensionPixelSize(R.styleable.WaterMarkView_wm_textSize, 50);
        textAlpha = typedArray.getFloat(R.styleable.WaterMarkView_wm_alpha, 0.3f);
        typedArray.recycle();
        textPaint.setAntiAlias(true);
        textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(textColor);
        textPaint.setTextSize(textSize);
        int alpha = (int) (textAlpha * 255);
        textPaint.setAlpha(alpha);
        SurfaceHolder surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
        setZOrderOnTop(true);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (texts != null && texts.size() > 0) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    draws();
                }
            });
            thread.start();
        }
    }

    private void draws() {
        SurfaceHolder surfaceHolder = getHolder();
        Canvas canvas = surfaceHolder.lockCanvas(null);
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        if (measuredWidth == 0 || measuredHeight == 0) {
            return;
        }
        //画布长度默认为屏幕长度
        int canvasLength = measuredWidth > measuredHeight ? measuredWidth : measuredHeight;
        //以屏幕中心点旋转一定角度
        canvas.rotate(degress, measuredWidth / 2, measuredHeight / 2);
        int ylocation = (measuredHeight - canvasLength) / 2;
        while (ylocation < canvasLength - (measuredHeight - canvasLength) / 2) {
            canvas.save();
            int xlocation = (measuredWidth - canvasLength) / 2;
            CoordinateModle coordinateModle = null;
            while (xlocation < canvasLength - (measuredWidth - canvasLength) / 2) {
                coordinateModle = drawWaterTextModule(xlocation, ylocation, canvas, texts);
                xlocation = xlocation + coordinateModle.getWtmWidth() + dx;
            }
            ylocation = ylocation + (coordinateModle == null ? 0 : coordinateModle.getWtmHeight()) + dy;
            canvas.restore();
        }
        surfaceHolder.unlockCanvasAndPost(canvas);
    }

    private CoordinateModle drawWaterTextModule(int xLocation, int yLocation, Canvas canvas, List<String> waterTexts) {
        int contentWidth = 0, contentHeight = 0, contentMaxLength = 0;
        int initXLocation = xLocation;
        int initYLocation = yLocation;
        Rect rect = new Rect();
        CoordinateModle coordinateModle = new CoordinateModle();
        for (int i = 0; i < waterTexts.size(); i++) {
            textPaint.getTextBounds(waterTexts.get(i), 0, waterTexts.get(i).length(), rect);
            if (contentWidth == 0) {
                contentWidth = rect.width();
                contentHeight = rect.height();
            } else {
                yLocation = yLocation + contentHeight + contentHeight / 2;
                xLocation = xLocation + contentWidth / 2;
                contentWidth = rect.width();
                contentHeight = rect.height();
                xLocation = xLocation - contentWidth / 2;
            }
            if (contentMaxLength < contentWidth)
                contentMaxLength = contentWidth;
            canvas.drawText(waterTexts.get(i), xLocation, yLocation, textPaint);
        }
        coordinateModle.setWtmWidth(contentMaxLength);
        coordinateModle.setWtmHeight(yLocation - initYLocation + contentHeight);
        return coordinateModle;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (thread != null) {
            thread.interrupt();
        }
    }

    public void updateWaterMarkConfig(WaterMarkConfig mWaterMarkConfig) {
        List<String> wtmTexts = mWaterMarkConfig.getWtmTexts();
        boolean showDataTime = mWaterMarkConfig.isShowDateTime();
        boolean showDeviceID = mWaterMarkConfig.isShowDeviceID();
        String wtmColor = mWaterMarkConfig.getWtmColor();
        int wtmSize = mWaterMarkConfig.getWtmTextSize();
        float wtmTransparency = mWaterMarkConfig.getWtmTransparency();
        List<String> wtmFinalTexts = new ArrayList<>();
        wtmFinalTexts.addAll(wtmTexts);
        if (showDataTime) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
            Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
            String time = formatter.format(curDate);
            wtmFinalTexts.add(time);
        }
        if (showDeviceID) {
            wtmFinalTexts.add(SystemUtils.getDevicesID(getContext()));
        }
        setWaterTexts(wtmFinalTexts);
        int color = Color.parseColor(wtmColor);
        setTextColor(color);
        setTextSize(wtmSize);
        setTextAlpha(wtmTransparency);
        refresh();
    }

    private void refresh() {
        textPaint.setColor(textColor);
        textPaint.setTextSize(textSize);
        int alpha = (int) (textAlpha * 255);
        textPaint.setAlpha(alpha);
    }

    public void setWaterTexts(List<String> list) {
        this.texts = list;
    }

    public void setTextColor(int color) {
        this.textColor = color;
    }

    public void setTextSize(int textSize) {
        this.textSize = textSize;
    }

    public void setTextAlpha(float textAlpha) {
        this.textAlpha = textAlpha;
    }

    /**
     * 水印模块的坐标及大小
     */
    private static class CoordinateModle {
        private int wtmWidth;
        private int wtmHeight;

        int getWtmWidth() {
            return wtmWidth;
        }

        void setWtmWidth(int wtmWidth) {
            this.wtmWidth = wtmWidth;
        }

        int getWtmHeight() {
            return wtmHeight;
        }

        void setWtmHeight(int wtmHeight) {
            this.wtmHeight = wtmHeight;
        }
    }
}